package com.zheng.api.server.controller;

import com.alibaba.fastjson.JSONObject;
import com.zheng.api.common.constant.ApiConstant;
import com.zheng.api.common.constant.ApiResult;
import com.zheng.api.common.constant.ApiResultConstant;
import com.zheng.api.server.constant.WeChatConfigure;
import com.zheng.api.server.service.ApiServerUmbrellaService;
import com.zheng.api.server.service.ApiServerWechatAppService;
import com.zheng.api.server.service.mq.um.Mq4UmbrellaMachineNotify;
import com.zheng.api.server.service.mq.um.Mq4UmbrellaWechatappNotify;
import com.zheng.business.dao.model.BusinessOrderUmbrellaConsumption;
import com.zheng.business.dao.model.BusinessOrderUmbrellaDeposit;
import com.zheng.business.dao.model.BusinessOrderUmbrellaRecharge;
import com.zheng.business.dao.model.BusinessOrderUmbrellaTimecard;
import com.zheng.common.base.BaseConstants;
import com.zheng.common.constant.Constant;
import com.zheng.common.exception.BaseException;
import com.zheng.common.util.*;
import com.zheng.umbrella.dao.model.*;
import com.zheng.umbrella.rpc.api.UmbrellaHardwareManageLogService;
import com.zheng.umbrella.rpc.api.UmbrellaHardwareMqttcommandLogService;
import com.zheng.upms.dao.model.UpmsDict;
import com.zheng.upms.dao.model.UpmsDictExample;
import com.zheng.upms.rpc.api.UpmsDictService;
import com.zheng.upms.rpc.api.UpmsSystemParamService;
import com.zheng.wechat.mp.dao.model.*;
import com.zheng.wechat.mp.rpc.api.WechatMpArticleService;
import com.zheng.wechat.mp.rpc.api.WechatMpCategoryService;
import com.zheng.wechat.mp.rpc.api.WechatMpFeedbackImageService;
import com.zheng.wechat.mp.rpc.api.WechatMpFeedbackService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import net.sf.json.JSONArray;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @Description: 伞机控制器
 * @author lvb
 * @date 2017-10-30
 * @version V1.0
 * @Copyright:
 */
@Controller
@Api(value = "小程序伞机业务控制器", description = "小程序伞机业务控制器")
@RequestMapping(value = "/v1/umbrella")
public class ApiUmbrellaController {

    private static final Logger LOGGER = LoggerFactory.getLogger(ApiUmbrellaController.class);

    @Autowired
    ApiServerWechatAppService apiServerWechatAppService;
    @Autowired
    ApiServerUmbrellaService apiServerUmbrellaService;

    @Autowired
    WechatMpCategoryService wechatMpCategoryService;
    @Autowired
    WechatMpArticleService wechatMpArticleService;

    @Autowired
    UmbrellaHardwareMqttcommandLogService umbrellaHardwareMqttcommandLogService;

    @Autowired
    WechatMpFeedbackService wechatMpFeedbackService;
    @Autowired
    WechatMpFeedbackImageService wechatMpFeedbackImageService;
    @Autowired
    UpmsDictService upmsDictService;
    @Autowired
    UmbrellaHardwareManageLogService umbrellaHardwareManageLogService;
//    @Autowired
//    WechatMpArticleImageService wechatMpArticleImageService;
    @Autowired
    Mq4UmbrellaMachineNotify mq4UmbrellaMachineNotify;
    @Autowired
    Mq4UmbrellaWechatappNotify mq4UmbrellaWechatappNotify;
    @Autowired
    UpmsSystemParamService upmsSystemParamService;


    @RequestMapping(value = "/getMachineInfos")
    @ApiOperation(value = "根据范围获取伞机数据")
    @ResponseBody
    public ApiResult getMachineInfos(@RequestParam String params) {
        LOGGER.info("###### 开始接收周边伞机数据请求 ######");

        try{
            JSONObject jsonParams = JsonUtil.getJSONObjectFromJson(params);
            //经纬度、距离
            String longitude = jsonParams.getString("longitude");
            String latitude = jsonParams.getString("latitude");
            String distance = jsonParams.getString("distance");
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            //客户端ip
            String ipAddress = RequestUtil.getIpAddr(request);

            List<UmbrellaHardwareMachine> machineInfos = apiServerUmbrellaService.getMachineInfos( longitude, latitude, distance, ipAddress);
            return new ApiResult(ApiResultConstant.SUCCESS,machineInfos);
        }catch (BaseException be){
            return new ApiResult(ApiResultConstant.FAILED,be.getMessage());
        }catch (Exception e){
            return new ApiResult(ApiResultConstant.FAILED,"服务器异常。");
        }
    }

    @RequestMapping(value = "/getRuleDeposit")
    @ApiOperation(value = "获取预付金规则")
    @ResponseBody
    public ApiResult getRuleDeposit(@RequestHeader Integer account,@RequestParam String machineCode) {
        try{
            LOGGER.info("###### 开始接收获取预付金规则请求 ######");
            //机器编号需要特殊处理
             machineCode = machineCode==null?"":machineCode.substring(machineCode.lastIndexOf("/")+1);if("null".equals(machineCode)){machineCode = "";}
            List<UmbrellaRuleDeposit> deposits = apiServerUmbrellaService.getRuleDeposit(account,machineCode);
            return new ApiResult(ApiResultConstant.SUCCESS,deposits);
        }catch (Exception e){
            return new ApiResult(ApiResultConstant.FAILED,"服务器异常");
        }
    }
    @RequestMapping(value = "/getRuleTimecard")
    @ApiOperation(value = "获取时长卡")
    @ResponseBody
    public ApiResult getRuleTimecard(@RequestHeader Integer account,@RequestHeader String machineCode) {
        try{
            LOGGER.info("###### 开始接收获取时长卡规则请求 ######");
            //机器编号需要特殊处理
            machineCode = machineCode==null?"":machineCode.substring(machineCode.lastIndexOf("/")+1);if("null".equals(machineCode)){machineCode = "";}
            List<UmbrellaRuleTimecard> deposits = apiServerUmbrellaService.getRuleTimecard(account,machineCode);
            JSONArray array = new JSONArray();
            for(UmbrellaRuleTimecard timecard : deposits){
                JSONObject obj = new JSONObject();
                obj.put("id", timecard.getId());
                obj.put("cardtype", timecard.getCardtype());
                obj.put("price", timecard.getPrice());
                obj.put("saleprice", timecard.getSaleprice());
                obj.put("description", timecard.getDescription());
                double discount = timecard.getSaleprice().doubleValue()/timecard.getPrice().doubleValue();
                if(discount>=1){
                    discount = 0;
                }
                obj.put("discount", String.format("%.1f", discount * 10));
                array.add(obj);
            }
            return new ApiResult(ApiResultConstant.SUCCESS,array);
        }catch (Exception e){
            return new ApiResult(ApiResultConstant.FAILED,"服务器异常");
        }
    }
    @RequestMapping(value = "/preparePayTimecard")
    @ApiOperation(value = "购买时长卡")
    @ResponseBody
    public String preparePayTimecard(@RequestHeader Integer account ,@RequestParam String params,@RequestHeader(value = "jwid", required = true, defaultValue = WeChatConfigure.WECHATAPP_GH)  String jwid) {
        LOGGER.info("###### 开始接收购买时长卡请求 ######");
        JSONObject jsonParams = JsonUtil.getJSONObjectFromJson(params);
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        Integer productId = jsonParams.getInteger("productId");
        String amount = jsonParams.getString("amount");
        //用户账号
        //String account = request.getHeader("account");

        //客户端ip
        String ipAddress = RequestUtil.getIpAddr(request);
        ApiResult apiResult = apiServerUmbrellaService.preparePayTimecard(account,productId,ipAddress,jwid);
        return JsonUtil.object2Json(apiResult);
    }
    @RequestMapping(value = "/getRuleRecharge")
    @ApiOperation(value = "获取充值规则")
    @ResponseBody
    public ApiResult getRuleRecharge(@RequestHeader Integer account,@RequestParam String machineCode) {
        LOGGER.info("###### 开始接收获取充值规则请求 ######");
        try{
            //伞机编号
            //机器编号需要特殊处理
             machineCode = machineCode==null?"":machineCode.substring(machineCode.lastIndexOf("/")+1);if("null".equals(machineCode)){machineCode = "";}
            List<UmbrellaRuleRecharge> ruleRecharges = apiServerUmbrellaService.getRuleRecharge(account,machineCode);
            return new ApiResult(ApiResultConstant.SUCCESS,ruleRecharges);
        }catch (Exception e){
            e.printStackTrace();;
            return new ApiResult(ApiResultConstant.FAILED,null);
        }
    }
    @RequestMapping(value = "/getRuleRent")
    @ApiOperation(value = "获取租金规则")
    @ResponseBody
    public ApiResult getRuleRent(@RequestParam String machineCode) {
        LOGGER.info("###### 开始接收获取租金规则请求 ######");
        try{
            //机器编号需要特殊处理
             machineCode = machineCode==null?"":machineCode.substring(machineCode.lastIndexOf("/")+1);if("null".equals(machineCode)){machineCode = "";}

            UmbrellaRuleRent ruleRent = apiServerUmbrellaService.getRuleRentByMachineCode(machineCode);
            return new ApiResult(ApiResultConstant.SUCCESS,ruleRent);
        }catch (BaseException be){
            return new ApiResult(ApiResultConstant.FAILED,be.getMessage());
        }catch (Exception e){
            return new ApiResult(ApiResultConstant.FAILED,"服务器异常。");
        }
    }
    @RequestMapping(value = "/prepareUmbrellaBorrowInfo")
    @ApiOperation(value = "预约借伞")
    @ResponseBody
    public String prepareUmbrellaBorrowInfo(@RequestParam String params) {
        LOGGER.info("###### 开始接收根据机器编号、account 下借伞订单请求 ######");
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String ipAddress = RequestUtil.getIpAddr(request);
        ApiResult apiResult = apiServerUmbrellaService.prepareUmbrellaScanBorrowInfo(params);
        return JsonUtil.object2Json(apiResult);
    }
    @RequestMapping(value = "/prepareUmbrellaReturnInfo")
    @ApiOperation(value = "预约还伞")
    @ResponseBody
    public String prepareUmbrellaReturnInfo(@RequestParam String params) {
        LOGGER.info("###### 开始接收根据机器编号、account 预约还伞请求 ######");
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String ipAddress = RequestUtil.getIpAddr(request);
        ApiResult apiResult = apiServerUmbrellaService.prepareUmbrellaScanReturnInfo(params);
        return JsonUtil.object2Json(apiResult);
    }


    @RequestMapping(value = "/manageUmbrellaIn")
    @ApiOperation(value = "开始进伞")
    @ResponseBody
    public String manageUmbrellaIn(@RequestParam String params) {
        LOGGER.info("###### 开始接收开始进伞请求 ######");
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        //客户端ip
        String ipAddress = RequestUtil.getIpAddr(request);
        ApiResult apiResult = apiServerUmbrellaService.manageUmbrellaIn(params);
        return JsonUtil.object2Json(apiResult);
    }

    @RequestMapping(value = "/manageUmbrellaEndIn")
    @ApiOperation(value = "结束进伞")
    @ResponseBody
    public String manageUmbrellaEndIn(@RequestParam String params) {
        LOGGER.info("###### 开始接收结束进伞请求 ######");
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        //客户端ip
        String ipAddress = RequestUtil.getIpAddr(request);
        ApiResult apiResult = apiServerUmbrellaService.manageUmbrellaEndIn(params);
        return JsonUtil.object2Json(apiResult);
    }

    @RequestMapping(value = "/manageUmbrellaOut")
    @ApiOperation(value = "开始出伞")
    @ResponseBody
    public String manageUmbrellaOut(@RequestParam String params) {
        LOGGER.info("###### 开始接收开始出伞请求 ######");
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        //客户端ip
        String ipAddress = RequestUtil.getIpAddr(request);
        ApiResult apiResult = apiServerUmbrellaService.manageUmbrellaOut(params);
        return JsonUtil.object2Json(apiResult);
    }

    @RequestMapping(value = "/manageUmbrellaEndOut")
    @ApiOperation(value = "结束出伞")
    @ResponseBody
    public String manageUmbrellaEndOut(@RequestParam String params) {
        LOGGER.info("###### 开始接收结束出伞请求 ######");
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        //客户端ip
        String ipAddress = RequestUtil.getIpAddr(request);
        ApiResult apiResult = apiServerUmbrellaService.manageUmbrellaEndOut(params);
        return JsonUtil.object2Json(apiResult);
    }
    @RequestMapping(value = "/getWechatCategoryByPid")
    @ApiOperation(value = "疑问指南")
    @ResponseBody
    public ApiResult getWechatCategoryByPid(@RequestParam Integer id) {
        LOGGER.info("###### 开始接收疑问指南请求 ######");
        try {
            WechatMpCategoryExample example = new WechatMpCategoryExample();
            example.createCriteria().andPidEqualTo(id);
            example.setOrderByClause("orders asc");
            List<WechatMpCategory> categoryList = wechatMpCategoryService.selectByExample(example);
            return new ApiResult(ApiResultConstant.SUCCESS,categoryList);
        }catch (Exception e){
            return new ApiResult(ApiResultConstant.FAILED,null);
        }
    }
    @RequestMapping(value = "/getWechatArticleByCategory")
    @ApiOperation(value = "获取文章集合")
    @ResponseBody
    public ApiResult getWechatArticleByCategory(@RequestParam Integer id,@RequestHeader(value = "jwid", required = true, defaultValue = WeChatConfigure.WECHATAPP_GH) String jwid) {
        LOGGER.info("###### 开始接收获取文章集合请求 ######");
        try {
            if(StringUtils.isEmpty(jwid)){
                jwid = WeChatConfigure.WECHATAPP_GH;
            }
            WechatMpArticleExample example = new WechatMpArticleExample();
            example.createCriteria().andCategoryIdEqualTo(id).andJwidEqualTo(jwid);
            example.setOrderByClause("orders asc");
            List<WechatMpArticle> categoryList = wechatMpArticleService.selectByExample(example);
            return new ApiResult(ApiResultConstant.SUCCESS,categoryList);
        }catch (Exception e){
            return new ApiResult(ApiResultConstant.FAILED,null);
        }
    }

    @ApiOperation(value = "反馈图片上传")
    @RequestMapping(value = "/uploadImage")
    @ResponseBody
    public ApiResult upload(@RequestHeader Integer account,@RequestParam(value = "fileData") MultipartFile file) throws IOException {
        try{
            String path = PropertiesUtil.getInstance().getValue(ApiConstant.UPLOAD_FILE_PATH) + "api";
            File f = new File(path);
            if (!f.exists())
                f.mkdirs();
            String name = file.getOriginalFilename();
            String prefix = name.substring(name.lastIndexOf("."));
            String fileName = UUID.randomUUID() + prefix;
            f = new File(path + "/" + fileName);
            if (!f.exists()) {
                f.createNewFile();
                file.transferTo(f);
            }
            RedisUtil.set("uploadFile"+account,fileName,3600);
            return new ApiResult(ApiResultConstant.SUCCESS,null);
        }catch (Exception e){
            return new ApiResult(ApiResultConstant.FAILED,null);
        }
    }

    @RequestMapping(value = "/feedbackStatus")
    @ApiOperation(value = "故障状态获取")
    @ResponseBody
    public ApiResult feedbackStatus() {
        LOGGER.info("###### 开始接收反馈请求 ######");
        try{
            UpmsDictExample example = new UpmsDictExample();
            UpmsDictExample.Criteria criteria = example.createCriteria();
            criteria.andFlagEqualTo(Constant.CONST_FLAG_NORMAL);
            criteria.andDicCodeEqualTo(BaseConstants.FEEDBACK_STATUS);
            List<UpmsDict> upmsDicts = upmsDictService.selectByExample(example);
            return new ApiResult(ApiResultConstant.SUCCESS,upmsDicts);
        }catch (Exception e){
            return new ApiResult(ApiResultConstant.FAILED,null);
        }
    }
    @RequestMapping(value = "/feedback")
    @ApiOperation(value = "反馈")
    @ResponseBody
    public ApiResult feedback(@RequestHeader Integer account ,WechatMpFeedback wechatMpFeedback) {
        LOGGER.info("###### 开始接收反馈请求 ######");
        try{
            wechatMpFeedback.setCtime(System.currentTimeMillis());
            wechatMpFeedback.setGzuserId(account);
            wechatMpFeedback.setStatus(0);
            Integer id = wechatMpFeedbackService.insertSelective(wechatMpFeedback,"id");
            String fileName = RedisUtil.get("uploadFile"+account);
            if(StringUtils.isNotBlank(fileName)){
                WechatMpFeedbackImage image = new WechatMpFeedbackImage();
                image.setImage(fileName);
                image.setFeedbackId(id);
                image.setPath(PropertiesUtil.getInstance().getValue(ApiConstant.UPLOAD_FILE_PATH) + "api/");
                image.setOrders(System.currentTimeMillis());
                wechatMpFeedbackImageService.insertSelective(image);
            }
            return new ApiResult(ApiResultConstant.SUCCESS,null);
        }catch (Exception e){
            return new ApiResult(ApiResultConstant.FAILED,null);
        }
    }

    @RequestMapping(value = "/prepareRecharge")
    @ApiOperation(value = "充值")
    @ResponseBody
    public String prepareRecharge(@RequestHeader Integer account ,@RequestParam String params,@RequestHeader(value = "jwid", required = true, defaultValue = WeChatConfigure.WECHATAPP_GH)  String jwid) {
        LOGGER.info("###### 开始接收充值请求 ######");
        JSONObject jsonParams = JsonUtil.getJSONObjectFromJson(params);
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        Integer productId = jsonParams.getInteger("productId");
        String amount = jsonParams.getString("amount");
        //用户账号
        //String account = request.getHeader("account");

        //客户端ip
        String ipAddress = RequestUtil.getIpAddr(request);
        ApiResult apiResult = apiServerUmbrellaService.prepareRecharge(account,productId,ipAddress,jwid);
        return JsonUtil.object2Json(apiResult);
    }
    @RequestMapping(value = "/preparePayDeposit")
    @ApiOperation(value = "缴纳预付金")
    @ResponseBody
    public String preparePayDeposit(@RequestHeader Integer account ,@RequestParam String params,@RequestHeader(value = "jwid", required = true, defaultValue = WeChatConfigure.WECHATAPP_GH)  String jwid) {
        LOGGER.info("###### 开始接收缴纳预付金请求 ######");
        JSONObject jsonParams = JsonUtil.getJSONObjectFromJson(params);
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        Integer productId = jsonParams.getInteger("productId");
        //String amount = jsonParams.getString("amount");
        //用户账号
        //String account = request.getHeader("account");

        //客户端ip
        String ipAddress = RequestUtil.getIpAddr(request);
        ApiResult apiResult = apiServerUmbrellaService.preparePayDeposit(account,productId,ipAddress,jwid);
        return JsonUtil.object2Json(apiResult);
    }
    @RequestMapping(value = "/prepareReturnDeposit")
    @ApiOperation(value = "退还预付金")
    @ResponseBody
    public String prepareReturnDeposit(@RequestHeader Integer account ,@RequestParam String params) {
        LOGGER.info("###### 开始接收退还预付金请求 ######");
        //JSONObject jsonParams = JsonUtil.getJSONObjectFromJson(params);
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        //用户账号
        //String account = request.getHeader("account");
        //客户端ip
        String ipAddress = RequestUtil.getIpAddr(request);
        //预约退款
        ApiResult apiResult = apiServerUmbrellaService.prepareReturnDeposit(account,ipAddress,false);
        return JsonUtil.object2Json(apiResult);
    }

    @RequestMapping(value = "/umbrellaLoss")
    @ApiOperation(value = "雨伞报失")
    @ResponseBody
    public ApiResult umbrellaLoss(@RequestHeader Integer account) {
        try {
            LOGGER.info("###### 开始处理雨伞报失 ###### account",account);
            BusinessOrderUmbrellaConsumption consumption = apiServerUmbrellaService.baseSelectBusinessOrderUmbrellaUnReturnByAccount(account,false);
            if(consumption!=null){
                apiServerUmbrellaService.completeBusinessOrderUmbrellaConsumption(consumption.getOrderno(),false,true,true);
            }else{
                return new ApiResult(ApiResultConstant.FAILED,"借伞订单不存在");
            }
            return new ApiResult(ApiResultConstant.SUCCESS,null);
        } catch (Exception e) {
            return new ApiResult(ApiResultConstant.FAILED,null);
        }
    }

    @RequestMapping(value = "/queryRechargeList")
    @ApiOperation(value = "查询充值记录")
    @ResponseBody
    public ApiResult queryRechargeList(@RequestHeader Integer account ,@RequestParam Integer page) {
        try {
            LOGGER.info("###### 开始接收查询充值记录请求 ######");
            List<BusinessOrderUmbrellaRecharge> recharges = apiServerUmbrellaService.queryRechargeList(account,page);
            JSONArray array = new JSONArray();
            DecimalFormat df = new DecimalFormat("0.00");
            for(BusinessOrderUmbrellaRecharge recharge : recharges){
                JSONObject obj = new JSONObject();
                obj.put("id", recharge.getId());
                obj.put("createtime", DateUtil.date2Str(recharge.getCreatetime()));
                obj.put("payamount", df.format(recharge.getPayamount().doubleValue()));
                array.add(obj);
            }
            return new ApiResult(ApiResultConstant.SUCCESS,array);
        } catch (Exception e) {
            return new ApiResult(ApiResultConstant.FAILED,null);
        }
    }
    @RequestMapping(value = "/queryDepositList")
    @ApiOperation(value = "查询预付金记录")
    @ResponseBody
    public ApiResult queryDepositList(@RequestHeader Integer account ,@RequestParam Integer page) {
        try {
            LOGGER.info("###### 开始接收查询预付金记录请求 ######");
            List<BusinessOrderUmbrellaDeposit> deposits = apiServerUmbrellaService.queryDepositList(account,page);
            JSONArray array = new JSONArray();
            DecimalFormat df = new DecimalFormat("0.00");
            for(BusinessOrderUmbrellaDeposit deposit : deposits){
                JSONObject obj = new JSONObject();
                obj.put("id", deposit.getId());
                obj.put("createtime", DateUtil.date2Str(deposit.getCreatetime()));
                obj.put("payamount", df.format(deposit.getRefundtime() != null ? -deposit.getPayamount().doubleValue():deposit.getPayamount().doubleValue()));
                array.add(obj);
            }
            return new ApiResult(ApiResultConstant.SUCCESS,array);
        } catch (Exception e) {
            return new ApiResult(ApiResultConstant.FAILED,null);
        }
    }

    @RequestMapping(value = "/queryMyTimecardList")
    @ApiOperation(value = "查询我的时长卡")
    @ResponseBody
    public ApiResult queryMyTimecardList(@RequestHeader Integer account,@RequestHeader String machineCode) {
        try {
            LOGGER.info("###### 开始接收查询时长卡记录请求 ######");
            List<BusinessOrderUmbrellaTimecard> timecards = apiServerUmbrellaService.queryMyTimecardList(account,machineCode);
            JSONArray array = new JSONArray();
            DecimalFormat df = new DecimalFormat("0.00");
            for(BusinessOrderUmbrellaTimecard timecard : timecards){
                JSONObject obj = new JSONObject();
                obj.put("id", timecard.getId());
                obj.put("createtime", DateUtil.date2Str(timecard.getCreatetime()));
                obj.put("payamount", df.format(timecard.getPayamount().doubleValue()));
                obj.put("cardType", timecard.getCardtype());
                obj.put("cardPreEndtime", DateUtil.date2Str(timecard.getCardPreEndtime()));
                obj.put("cardAfterEndtime", DateUtil.date2Str(timecard.getCardAfterEndtime()));
                array.add(obj);
            }
            return new ApiResult(ApiResultConstant.SUCCESS,array);
        } catch (Exception e) {
            return new ApiResult(ApiResultConstant.FAILED,null);
        }
    }

    @RequestMapping(value = "/queryTimecardList")
    @ApiOperation(value = "查询时长卡记录")
    @ResponseBody
    public ApiResult queryTimecardList(@RequestHeader Integer account ,@RequestParam Integer page,@RequestHeader String machineCode) {
        try {
            LOGGER.info("###### 开始接收查询时长卡记录请求 ######");
            List<BusinessOrderUmbrellaTimecard> timecards = apiServerUmbrellaService.queryTimecardList(account,machineCode,page);
            JSONArray array = new JSONArray();
            DecimalFormat df = new DecimalFormat("0.00");
            for(BusinessOrderUmbrellaTimecard timecard : timecards){
                JSONObject obj = new JSONObject();
                obj.put("id", timecard.getId());
                obj.put("createtime", DateUtil.date2Str(timecard.getCreatetime()));
                obj.put("payamount", df.format(timecard.getPayamount().doubleValue()));
                obj.put("cardType", timecard.getCardtype());
                obj.put("cardPreEndtime", DateUtil.date2Str(timecard.getCardPreEndtime()));
                obj.put("cardAfterEndtime", DateUtil.date2Str(timecard.getCardAfterEndtime()));
                array.add(obj);
            }
            return new ApiResult(ApiResultConstant.SUCCESS,array);
        } catch (Exception e) {
            return new ApiResult(ApiResultConstant.FAILED,null);
        }
    }
    @RequestMapping(value = "/currentConsumption")
    @ApiOperation(value = "获取当前未结算订单")
    @ResponseBody
    public ApiResult currentConsumption(@RequestHeader Integer account) {
        try{
            LOGGER.info("###### 开始接收查询雨伞借还记录请求 ######");
            BusinessOrderUmbrellaConsumption consumption = apiServerUmbrellaService.baseSelectBusinessOrderUmbrellaUnReturnByAccount(account,true);
            UmbrellaRuleRent rent = apiServerUmbrellaService.baseSelectUmbrellaRuleRentNoCache(consumption.getRentRuleId(),false);
            if(rent==null) {
                return new ApiResult(ApiResultConstant.FAILED, null);
            }
            //String dictText = upmsDictService.queryDataDictTextByValue(Constant.UM_RULE_TYPE,rent.getChargetype().toString());

            Date nowDate = new Date();
            //long time = currentDate.getTime() - consumption.getBegintime().getTime();
            JSONObject order = new JSONObject();
            order.put("orderno",consumption.getOrderno());
            order.put("begintime",DateUtil.date2Str(consumption.getBegintime()));

            String dictText = upmsDictService.queryDataDictTextByValue(Constant.UM_RULE_TYPE,rent.getChargetype().toString());
            String freeDictText = upmsDictService.queryDataDictTextByValue(Constant.UM_RULE_TYPE,rent.getFreetimetype().toString());
            StringBuffer ruleTrans = new StringBuffer();
            ruleTrans.append("￥").append(rent.getPrice()).append("/").append(rent.getChargelength()).append(dictText);
            if(rent.getFreetimelength()>0) {
                ruleTrans.append("，免费时长：").append(rent.getFreetimelength()).append(freeDictText);
            }
            ruleTrans.append("，不足").append(rent.getChargelength()).append(dictText).append("按").append(rent.getChargelength()).append(dictText).append("计。");
            order.put("rent",ruleTrans.toString());
            order.put("duration",DateUtil.covertIntervalDDHHMI(consumption.getBegintime(),nowDate));
            DecimalFormat df = new DecimalFormat("0.00");
            order.put("charge", df.format(apiServerUmbrellaService.calculateOrderCost(consumption,rent)));
            if(consumption.getAutoendtime()!=null) {
                //业务处理最晚还伞时间需+1，取凌晨0点
                order.put("autoendtime", DateUtil.date2Str(DateUtil.addDate(consumption.getAutoendtime(), 1),DateUtil.FORMAT_YYYY_MM_DD));
            }else{
                order.put("autoendtime",null);
            }
            return new ApiResult(ApiResultConstant.SUCCESS,order);
        } catch (Exception e) {
            return new ApiResult(ApiResultConstant.FAILED,null);
        }
    }

    @RequestMapping(value = "/queryConsumptionList")
    @ApiOperation(value = "查询雨伞借还记录")
    @ResponseBody
    public ApiResult queryConsumptionList(@RequestHeader Integer account ,@RequestParam Integer page) {
        try{
            LOGGER.info("###### 开始接收查询雨伞借还记录请求 ######");
            List<BusinessOrderUmbrellaConsumption> consumptions = apiServerUmbrellaService.queryConsumptionList(account,page);
            JSONArray array = new JSONArray();
            DecimalFormat df = new DecimalFormat("0.00");
            for(BusinessOrderUmbrellaConsumption consumption : consumptions){
                JSONObject obj = new JSONObject();
                obj.put("orderno", consumption.getOrderno());
                obj.put("begintime", DateUtil.date2Str(consumption.getBegintime()));
                obj.put("endtime",  DateUtil.date2Str(consumption.getEndtime()));
                obj.put("rentamount",  df.format(consumption.getRentamount()!=null ? consumption.getRentamount().doubleValue() : 0));
                obj.put("payamount",  df.format(consumption.getPayamount()!=null ? consumption.getPayamount().doubleValue() : 0));
                obj.put("discountedamount",  df.format(consumption.getDiscountedamount()!=null ? consumption.getDiscountedamount().doubleValue() : 0));
                array.add(obj);
            }
            return new ApiResult(ApiResultConstant.SUCCESS,array);
        } catch (Exception e) {
            return new ApiResult(ApiResultConstant.FAILED,null);
        }
    }

    @RequestMapping(value = "/manageUmbrellaHistory")
    @ApiOperation(value = "进出伞记录")
    @ResponseBody
    public ApiResult manageUmbrellaHistory(@RequestHeader Integer account,@RequestParam Integer page) {
        try{
            LOGGER.info("###### 开始接收进出伞记录请求 ######");

            Integer rows = 10;
            Integer tmpPage = StringUtil.getInt(page, 1);

            UmbrellaHardwareManageLogExample example = new UmbrellaHardwareManageLogExample();
            UmbrellaHardwareManageLogExample.Criteria criteria = example.createCriteria();
            List<String> commondList = new ArrayList<>();
            commondList.add(ApiConstant.UMBRELLA_MACHINE_COMMAND_10110);
            commondList.add(ApiConstant.UMBRELLA_MACHINE_COMMAND_10112);
            criteria.andCommandIn(commondList);
            criteria.andUseridEqualTo(account);
            criteria.andResultEqualTo(1);

            Integer total = umbrellaHardwareManageLogService.countByExample(example);
            Integer offset = (tmpPage - 1) * rows;
            List<UmbrellaHardwareManageLog> logs = new ArrayList<UmbrellaHardwareManageLog>();
            if(offset<total){
                logs = umbrellaHardwareManageLogService.selectByExampleForOffsetPage(example, (tmpPage - 1) * rows, rows);
            }
            JSONArray array = new JSONArray();
            for(UmbrellaHardwareManageLog log : logs){
                JSONObject obj = new JSONObject();
                obj.put("orderno", log.getOrderno());
                obj.put("startTime", DateUtil.date2Str(log.getStartTime()));
                obj.put("endTime",  DateUtil.date2Str(log.getEndTime()));
                obj.put("machineCode",log.getMachineCode());
                obj.put("umbrellacount",  log.getUmbrellacount());
                obj.put("umbrellalist",  log.getUmbrellalist());
                obj.put("command",  ApiConstant.UMBRELLA_MACHINE_COMMAND_10110.equals(log.getCommand())?"进伞":"出伞");
                array.add(obj);
            }
            return new ApiResult(ApiResultConstant.SUCCESS,array);
        } catch (Exception e) {
            return new ApiResult(ApiResultConstant.FAILED,null);
        }
    }

    @RequestMapping(value = "/manageCommandLog")
    @ApiOperation(value = "指令记录")
    @ResponseBody
    public ApiResult manageCommandLog() {
        try{
            LOGGER.info("###### 开始接收指令记录请求 ######");

            UmbrellaHardwareMqttcommandLogExample example = new UmbrellaHardwareMqttcommandLogExample();
            example.setOrderByClause("req_time desc");

            UmbrellaHardwareMqttcommandLogExample.Criteria criteria = example.createCriteria();
            criteria.andReqCommandNotEqualTo(ApiConstant.UMBRELLA_MACHINE_COMMAND_20002);
            criteria.andReqCommandLike("2%");
//            UmbrellaHardwareMqttcommandLogExample.Criteria criteria1 = example.createCriteria();
//            criteria1.andReqCommandLike("2%");
//            example.or(criteria1);
            List<UmbrellaHardwareMqttcommandLog> commandLogList = umbrellaHardwareMqttcommandLogService.selectByExampleForOffsetPage(example, 0, 10);
            JSONArray array = new JSONArray();
            for(UmbrellaHardwareMqttcommandLog log : commandLogList){
                JSONObject obj = new JSONObject();
                obj.put("reqTime", DateUtil.date2Str(log.getReqTime()));
                obj.put("reqMachineCode", StringUtil.toString(log.getReqMachineCode()));
                obj.put("reqCommand",  StringUtil.toString(log.getReqCommand()));
                obj.put("reqCode",StringUtil.toString(log.getReqCode()));
                obj.put("reqData",  StringUtil.toString(log.getReqData()));
                obj.put("resCommand", StringUtil.toString(log.getResCommand()));
                obj.put("resCode",  StringUtil.toString(log.getResCode()));
                obj.put("resData",  StringUtil.toString(log.getResData()));
                array.add(obj);
            }
            return new ApiResult(ApiResultConstant.SUCCESS,array);
        } catch (Exception e) {
            return new ApiResult(ApiResultConstant.FAILED,null);
        }
    }
    @RequestMapping(value = "/getMachineIsOnline")
    @ApiOperation(value = "获取伞机在线状态")
    @ResponseBody
    public ApiResult getMachineIsOnline(@RequestParam String params,@RequestHeader String machineCode) {
        LOGGER.info("###### 开始接收获取伞机在线状态请求 ######");
        try{
            JSONObject jsonParams = JsonUtil.getJSONObjectFromJson(params);
            String queryMachineCode = jsonParams.getString("machineCode");
            queryMachineCode =  StringUtils.isEmpty(queryMachineCode)? machineCode:queryMachineCode;

            //机器编号需要特殊处理
            queryMachineCode = StringUtils.isEmpty(queryMachineCode)?"":queryMachineCode.substring(queryMachineCode.lastIndexOf("/")+1);
            UmbrellaHardwareMachine machineInfo = apiServerUmbrellaService.baseSelectUmbrellaHardwareMachineByStatus( queryMachineCode,true);
            if(machineInfo!=null){
                //在线
                return new ApiResult(ApiResultConstant.SUCCESS, true);
            }else {
                //不在线或无效伞机
                return new ApiResult(ApiResultConstant.SUCCESS, false);
            }
        }catch (Exception e){
            return new ApiResult(ApiResultConstant.FAILED,"服务器异常。");
        }
    }

    /**
     * 接收支付中心支付结果通知
     */
    @ApiIgnore
    @RequestMapping("/payBusinessNotify.htm")
    @ApiOperation(value = "接收支付中心支付结果通知")
    @ResponseBody
    public String payBusinessNotify() {
        LOGGER.info("====== 开始接收支付中心支付结果通知 ======");
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String result = apiServerUmbrellaService.payBusinessNotify(request);
        LOGGER.info("====== 接收支付中心支付结果通知完成 ======");
        return result;
    }
    /**
     * 接收支付中心退款通知
     */
    @ApiIgnore
    @RequestMapping("/refundBusinessNotify.htm")
    @ApiOperation(value = "接收支付中心退款通知")
    @ResponseBody
    public String refundBusinessNotify() {
        LOGGER.info("====== 开始接收支付中心退款通知 ======");
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String result = apiServerUmbrellaService.refundBusinessNotify(request);
        LOGGER.info("====== 接收支付中心退款通知完成 ======");
        return result;
    }
    /**
     * 接收第三方预付金订单退还请求
     */
    @ApiIgnore
    @RequestMapping("/returnBusinessDepositUmbrellaConsumption.htm")
    @ApiOperation(value = "接收第三方预付金订单退还请求")
    @ResponseBody
    public String returnBusinessDepositUmbrellaConsumption(@RequestParam Integer account,
                                                           @RequestParam boolean isForce) {
        LOGGER.info("====== 接收第三方预付金订单退还请求 ======");
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        //用户账号
        //String account = request.getHeader("account");
        //客户端ip
        String ipAddress = RequestUtil.getIpAddr(request);
        //预约退款
        ApiResult apiResult = apiServerUmbrellaService.prepareReturnDeposit(account,ipAddress,isForce);
        LOGGER.info("====== 处理第三方预付金订单退还请求完成 ======");
        return JsonUtil.object2Json(apiResult);
    }
    /**
     * 接收雨伞订单结算通知
     */
    @ApiIgnore
    @RequestMapping("/closeBusinessOrderUmbrellaConsumption.htm")
    @ApiOperation(value = "接收雨伞订单结算通知")
    @ResponseBody
    public String closeBusinessOrderUmbrellaConsumption(@RequestParam String orderNo,@RequestParam boolean isCharge,@RequestParam boolean isLoss) {
        LOGGER.info("====== 开始接收雨伞订单结算通知 ======");
        //HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        apiServerUmbrellaService.completeBusinessOrderUmbrellaConsumption(orderNo,false,isCharge,isLoss);
        LOGGER.info("====== 处理雨伞订单结算通知完成 ======");
        return "SUCCESS";
    }
    /**
     * 接收伞机重启指令
     */
    @ApiIgnore
    @RequestMapping("/rebootUmbrellaMachine.htm")
    @ApiOperation(value = "接收伞机重启指令")
    @ResponseBody
    public String rebootUmbrellaMachine(@RequestParam String codes) {
        LOGGER.info("====== 开始接收伞机重启指令 ======");
        //HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        try {
            /**
             * {"command":"10003","machineCode":"dev0001","code":1,"message":"","data":{"serialNo":"20180929100020001","dataPackage":{"account":10000004,"token":"SDKJLJBB_JLKSDJFLKDSJFDSJFLJ-IJOIUEWRPOI"}}}
             */
            String machineCodes[] = codes.split(",");
            //业务流水号
            String bizSeqNo = BizSequenceUtils.getInstance().generateBizSeqNo(ModuleConstant.UMBRELLA_COMMON_BIZ_SEQUENCE_NO_PREFIX);
            for(Integer i=0 ; i<machineCodes.length ; i++){
                String machineCode = machineCodes[i];
                JSONObject machineDataInfo = new JSONObject();
                JSONObject dataPackage = new JSONObject();
                dataPackage.put("account",10000004);
                dataPackage.put("token","SDKJLJBB_JLKSDJFLKDSJFDSJFLJ-IJOIUEWRPOI");
                machineDataInfo.put("serialNo", bizSeqNo);
                machineDataInfo.put("dataPackage", dataPackage);

                ApiResult machineNotifyInfo = new ApiResult(ApiResultConstant.SUCCESS.code, ApiResultConstant.SUCCESS.message, ApiConstant.UMBRELLA_MACHINE_COMMAND_10003, machineCode, machineDataInfo);
                mq4UmbrellaMachineNotify.send(JsonUtil.object2Json(machineNotifyInfo), machineCode);

            }
        }catch(Exception e){
            LOGGER.error("重启失败",e.getCause());
        }
        LOGGER.info("====== 处理接收伞机重启指令完成 ======");
        return "SUCCESS";
    }
    /**
     * 接收雨伞订单免单通知
     */
    @ApiIgnore
    @RequestMapping("/freeBusinessOrderUmbrellaConsumption.htm")
    @ApiOperation(value = "接收雨伞订单免单通知")
    @ResponseBody
    public String freeBusinessOrderUmbrellaConsumption(@RequestParam String orderNo) {
        LOGGER.info("====== 开始接收雨伞订单免单通知 ======");
        //HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        apiServerUmbrellaService.freeBusinessOrderUmbrellaConsumption(orderNo);
        LOGGER.info("====== 处理雨伞订单免单通知完成 ======");
        return "SUCCESS";
    }
}
